import { Inject, Injectable, NotFoundException } from '@nestjs/common';
import {
  CreateComponyUserDto,
  CreateUserDto,
  LeaveCompanyUser,
  QueryInfo,
  QueryInfoCompanyUser,
  UpdateCompanyDto,
} from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import * as jwt from 'jsonwebtoken';
import { encodePwd, generateRandomString } from 'src/utils';

@Injectable()
export class UserService {
  @Inject()
  private prisma: PrismaService;
  // 管理员创建账号
  async createAccount(createUserDto: CreateUserDto, token: string) {
    const decoded = jwt.verify(token, 'cvnert') as any;
    const admin = await this.prisma.admin.findUnique({
      where: {
        id: decoded.id,
      },
    });

    if (!admin) {
      return '不是管理员账号';
    }
    const { employeeNum, ...newObject } = createUserDto;
    return await this.prisma.$transaction(async (tx) => {
      // 创建公司账号
      const password = generateRandomString(8);
      console.log('密码公司：', password);
      const company = await tx.company.create({
        data: {
          userName: createUserDto.name,
          password: encodePwd(password),
          isValid: true,
          ...newObject,
        },
      });
      if (employeeNum && employeeNum > 0) {
        // 批量创建公司账号
        const employees = Array.from({ length: employeeNum }).map(
          (_, index) => ({
            userName: `emp_${generateRandomString(4)}`, // 生成唯一用户名
            password: encodePwd('123456'), // 随机密码
            companyId: company.id,
            isValid: true,
          }),
        );
        await tx.companyUser.createMany({
          data: employees,
        });
      }
      return {
        message: '公司和员工账号创建成功',
        company,
        password,
        employeeCount: employeeNum || 0,
      };
    });
  }

  // 管理员或者公司账号通过公司id查询公司员工账号同一密码123456
  async findAll(companyId: string, token: string) {
    const decoded = jwt.verify(token, 'cvnert') as any;
    const admin = await this.prisma.admin.findUnique({
      where: {
        id: decoded.id,
      },
    });
    const companyUser = await this.prisma.companyUser.findMany({
      where: {
        id: decoded.id,
      },
    });

    if (!admin || !companyUser) {
      return '你没有权限';
    }
    // 检查公司是否存在
    const company = await this.prisma.company.findUnique({
      where: { id: companyId },
    });

    if (!company) {
      throw new NotFoundException('公司不存在');
    }
    // 查询该公司下的所有员工
    const employees = await this.prisma.companyUser.findMany({
      where: { companyId },
      orderBy: { createdAt: 'asc' }, // 按创建时间排序
    });
    return {
      companyId,
      companyName: company.name, // 假设 company 的 user 字段是公司名称
      employeeCount: employees.length,
      employees,
    };
  }

  // 管理员查询所有公司
  async getAllCompanies(query: QueryInfo, token: string) {
    try {
      const decoded = jwt.verify(token, 'cvnert') as any;
      const admin = await this.prisma.admin.findUnique({
        where: {
          id: decoded.id,
        },
      });

      if (!admin) {
        return '不是管理员账号';
      }
      //分页
      let { page, per, name, isValid } = query;
      if (!page) {
        page = 1;
      }
      if (!per) {
        per = 10;
      }
      //模糊查询
      const where = {
        AND: [
          name
            ? {
                name: {
                  contains: name,
                },
              }
            : {},
          typeof isValid === 'boolean'
            ? {
                isValid: isValid, // 直接使用布尔值比较
              }
            : {},
        ].filter(Boolean), // 过滤空条件
      };
      // 查询所有公司
      const companies = await this.prisma.company.findMany({
        where,
        skip: (page - 1) * per,
        take: per,
      });
      const total = await this.prisma.company.count({
        where,
      });
      return {
        code: 200,
        message: '查询成功',
        data: {
          companies,
          total,
        },
      };
    } catch (error) {}
  }
  // 查看公司是否在有效期
  async checkCompanyValid(companyId: string, token: string) {
    const decoded = jwt.verify(token, 'cvnert') as any;
    const admin = await this.prisma.admin.findUnique({
      where: {
        id: decoded.id,
      },
    });

    if (!admin) {
      return '不是管理员账号';
    }
    const company = await this.prisma.company.findUnique({
      where: {
        id: companyId,
      },
    });
    if (!company) {
      return '公司不存在';
    }
    const { expirationAt } = company;
    const dataObj = new Date(expirationAt);
    const currentDate = new Date();

    const timeDiff = currentDate.getTime() - dataObj.getTime();
    const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
    if (daysDiff >= 0) {
      await this.prisma.company.update({
        where: {
          id: companyId,
        },
        data: {
          isValid: false,
        },
      });
      return {
        message: '公司已过期',
        data: false,
      };
    } else {
      return {
        message: '公司未过期',
        data: true,
      };
    }
  }

  // 管理员手动续费
  async renewCompany(companyId: string, token: string, time: Date) {
    const decoded = jwt.verify(token, 'cvnert') as any;
    const admin = await this.prisma.admin.findUnique({
      where: {
        id: decoded.id,
      },
    });

    if (!admin) {
      return '不是管理员账号';
    }
    const res = await this.prisma.company.update({
      where: {
        id: companyId,
      },
      data: {
        expirationAt: time,
        isValid: true,
      },
    });
    if (res) {
      return {
        code: 200,
        message: '续费成功',
      };
    } else {
      return {
        code: 400,
        message: '续费失败',
      };
    }
  }
  // 管理员手动冻结
  async freezeCompany(companyId: string, token: string) {
    const decoded = jwt.verify(token, 'cvnert') as any;
    const admin = await this.prisma.admin.findUnique({
      where: {
        id: decoded.id,
      },
    });

    if (!admin) {
      return '不是管理员账号';
    }
    console.log('companyId', companyId);
    const res = await this.prisma.company.update({
      where: {
        id: companyId,
      },
      data: {
        isValid: false,
      },
    });
    const res1 = await this.prisma.companyUser.updateMany({
      where: {
        companyId,
      },
      data: {
        isValid: false,
      },
    });
    if (res && res1) {
      return {
        code: 200,
        message: '冻结成功',
      };
    } else {
      return {
        code: 400,
        message: '冻结失败',
      };
    }
  }

  // 管理员或者公司账号通过公司id查询公司所有的员工
  async findAllInCompany(query: QueryInfoCompanyUser, token: string) {
    const decoded = jwt.verify(token, 'cvnert') as any;
    const admin = await this.prisma.admin.findUnique({
      where: {
        id: decoded.id,
      },
    });

    const companyUser = await this.prisma.companyUser.findMany({
      where: {
        companyId: query.companyId,
      },
    });

    if (!admin || !companyUser) {
      return '你没有权限';
    }
    //分页
    let { page, per, name, isLeave } = query;
    if (!page) {
      page = 1;
    }
    if (!per) {
      per = 10;
    }
    //模糊查询
    const where = {
      AND: [
        name
          ? {
              name: {
                contains: name,
              },
            }
          : {},
        typeof isLeave === 'boolean'
          ? {
              isLeave: isLeave,
            }
          : {},
      ],
    };
    // 查询所有员工
    const users = await this.prisma.user.findMany({
      where,
      skip: (page - 1) * per,
      take: per,
    });
    const total = await this.prisma.user.count({
      where,
    });
    return {
      code: 200,
      message: '查询成功',
      data: {
        users,
        total,
      },
    };
  }
  // 录入公司员工
  async create(createUserDto: CreateComponyUserDto, token: string) {
    const decoded = jwt.verify(token, 'cvnert') as any;
    const admin = await this.prisma.admin.findUnique({
      where: {
        id: decoded.id,
      },
    });
    const companyUser = await this.prisma.companyUser.findFirst({
      where: {
        id: admin.id,
      },
    });

    const company = await this.prisma.company.findUnique({
      where: {
        id: admin.id,
      },
    });

    // 如果是管理员，需要前端传入公司信息
    if (admin) {
      if (createUserDto.companyId) {
        const res = await this.prisma.user.create({
          data: {
            ...createUserDto,
          },
        });
        return {
          code: 200,
          message: '创建成功',
          data: res,
        };
      } else {
        return '公司id不能为空';
      }
    }
    // 如果是公司员工账号或者公司账号，公司id则只能是本公司
    if (companyUser || company) {
      const { companyId } = companyUser;
      const res = await this.prisma.user.create({
        data: {
          ...createUserDto,
          companyId,
        },
      });
      return {
        code: 200,
        message: '创建成功',
        data: res,
      };
    }
  }

  // 员工离职
  async leaveCompanyUser(leaveCompanyUser: LeaveCompanyUser, token: string) {
    const decoded = jwt.verify(token, 'cvnert') as any;
    const companyUser = await this.prisma.companyUser.findUnique({
      where: {
        id: decoded.id,
      },
    });
    const company = await this.prisma.company.findUnique({
      where: {
        id: decoded.id,
      },
    });
    if (companyUser || company) {
      const res = await this.prisma.user.update({
        where: {
          id: leaveCompanyUser.id,
        },
        data: {
          isLeave: true,
        },
      });
      if (res) {
        return {
          message: '离职成功',
          code: 200,
        };
      }
    }
  }

  // 公司账号修改密码或者公司信息
  async updateCompanyInfo(updateCompanyDto: UpdateCompanyDto, token: string) {
    const decoded = jwt.verify(token, 'cvnert') as any;
    const companyUser = await this.prisma.company.findUnique({
      where: {
        id: decoded.id,
      },
    });
    if (!companyUser) {
      return '不是公司账号';
    }
    const { id } = companyUser;
    const res = await this.prisma.company.update({
      where: {
        id,
      },
      data: {
        password: updateCompanyDto.password,
        CompanyIcon: updateCompanyDto.CompanyIcon,
      },
    });
    if (res) {
      return {
        message: '修改成功',
      };
    }
  }

  // 查看当前登录的账号
  async getCurrentUser(token: string) {
    const decoded = jwt.verify(token, 'cvnert') as any;
    const admin = await this.prisma.admin.findFirst({
      where: {
        id: decoded.id,
      },
    });
    const companyPersonUser = await this.prisma.companyUser.findFirst({
      where: {
        id: decoded.id,
      },
    });
    const companyUser = await this.prisma.company.findFirst({
      where: {
        id: decoded.id,
      },
    });
    if (admin) {
      return {
        code: 200,
        message: '查询成功',
        data: {
          user: admin,
          role: 'admin',
        },
      };
    }
    if (companyUser) {
      return {
        code: 200,
        message: '查询成功',
        data: {
          user: companyUser,
          role: 'company',
        },
      };
    }
    if (companyPersonUser) {
      return {
        code: 200,
        message: '查询成功',
        data: {
          user: companyPersonUser,
          role: 'companyUser',
        },
      };
    }
  }

  // 查询单个用户信息
  async findOne(id: string) {
    return await this.prisma.user.findUnique({
      where: {
        id,
      },
    });
  }

  // 获取单个公司信息
  async getOneCompanyInfo(companyId: string, token: string) {
    const decoded = jwt.verify(token, 'cvnert') as any;
    const admin = await this.prisma.admin.findUnique({
      where: {
        id: decoded.id,
      },
    });

    if (!admin) {
      return '不是管理员账号';
    }
    return await this.prisma.company.findUnique({
      where: {
        id: companyId,
      },
    });
  }
}
